package com.example.user.service.user;

import com.example.framework.common.exception.ServiceException;
import com.example.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.example.framework.common.util.json.JsonUtils;
import com.example.user.controller.auth.vo.UserSourceType;
import com.example.user.service.admin.AdminUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private AdminUserService adminUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserSourceType userSourceType = JsonUtils.parseObject(username, UserSourceType.class);
        if (Objects.isNull(userSourceType)) {
            throw ServiceException.of(GlobalErrorCodeConstants.USER_NOT_FOUND);
        }
        if (userSourceType.getAdmin()) {
            return adminUserService.loadLoginUserByUserSourceType(userSourceType);
        } else {
            return userService.loadLoginUserByUserSourceType(userSourceType);
        }
    }
}
